package com.dahaonetwork.smartfactory.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.redis.JdkSerializationStrategy;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStoreSerializationStrategy;



public class UserModelUtil {

	private static final Logger log = LoggerFactory.getLogger(UserModelUtil.class);  

	/** session中认证信息键值 */
	public static final String SESSION_AUTHEN_ATTR_NAME = "SPRING_SECURITY_CONTEXT";

	/**
	 * @Title: getUserModel
	 * @Description 提取认证服务器返回的UserModel信息<br>
	 * 获取过程中，先根据载体获取原userModel
	 * 若已经实现com.jb.listener.client.Listener，并发布成service，并按照通用接口扩展规则使用，即可按照您的需求进行扩展userModel
	 * @param carrier 经过认证服务器包装的OAuth2Authentication实例或HttpSession
	 * @return UserModel
	 */
	public static String getUserModel(Object carrier){

		String userModel = null;

		if(carrier instanceof HttpSession) {// 使用spring session
			Object obj = ((HttpSession) carrier).getAttribute(SESSION_AUTHEN_ATTR_NAME);
			if(obj instanceof SecurityContextImpl){
				SecurityContextImpl securityContext = (SecurityContextImpl) obj;
				userModel = securityContext.getAuthentication().getPrincipal().toString();
			}else{
				log.error("该httpSession实例中无用户验证信息，不能获取到认证服务器提供的UserModel。");
			}
		}else if (carrier instanceof OAuth2Authentication){//原方案【每个微服务均进行认证】
			OAuth2Authentication oauthen = (OAuth2Authentication) carrier;
			userModel = oauthen.getPrincipal().toString();
		}else {
			log.error("该实例非OAuth2Authentication或者httpSession实现，不能获取到认证服务器提供的UserModel。");
			// 若无，直接返回null
			return null;
		}
		return userModel;
	}
}
